package com.i2863.receipt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.i2863.receipt.entity.Account;
import com.i2863.receipt.entity.Site;
import com.i2863.receipt.service.AccountService;
import com.i2863.receipt.service.SiteService;
import com.i2863.receipt.userUtil.Constant;
import com.i2863.receipt.userUtil.User;
import com.i2863.receipt.userUtil.UserCenter;
import com.i2863.receipt.util.HttpSessionUtils;
import com.i2863.receipt.util.Md5Util;
import com.i2863.receipt.util.ResultJson;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/6/8.
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    private static CloseableHttpClient client = HttpSessionUtils.buildHttpClient();


    /**
     * 跳转到登陆页
     * @param serverError
     * @param usernameError
     * @param passwordError
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/toLogin",produces = "text/html;charset=UTF-8")
    public String toLogin(@ModelAttribute(value = "serverError")String serverError,
                          @ModelAttribute(value = "usernameError")String usernameError,
                          @ModelAttribute(value = "passwordError")String passwordError,
                          ModelMap modelMap){
        modelMap.put("serverError",serverError);
        modelMap.put("usernameError",usernameError);
        modelMap.put("passwordError",passwordError);
        return "login";
    }

    /**
     * 后台首页
     * @return
     */
    @RequestMapping("/main")
    public String main(){
        return "welcome";
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/quit")
    public String quit(){
        HttpSession session = request.getSession();
        session.invalidate();
        return "login";
    }

    @RequestMapping(value = "/login",produces = "text/html;charset=UTF-8")
    public String login(String username,String password,RedirectAttributes attr){
        Boolean flag = true;
        Account account = null;

        //验证用户名
        if(username==null||username.equals("")){
            attr.addFlashAttribute("usernameError","用户名不能为空");
            flag = false;
            return "redirect:toLogin";
        }else{
            account = accountService.findByUsername(username);
            if(account==null){
                attr.addFlashAttribute("usernameError","用户不存在");
                flag = false;
                return "redirect:toLogin";
            }
        }

        //验证密码
        if(password==null||password.equals("")){
            attr.addFlashAttribute("passwordError","密码不能为空");
            flag = false;
            return "redirect:toLogin";
        }else{
            //密码验证调用户中心
            Map<String, String> param = new HashMap<String, String>(20);
            //构造请求参数
            param.put("method", "login");
            param.put("username", username);
            param.put("siteId", "136");
            param.put("password", Md5Util.encrypt(password));
            String jsonStr = null;
            try {
                jsonStr = HttpSessionUtils.httpPost(client,Constant.ucenter,param);
            }catch(IOException e){//请求失败
                attr.addFlashAttribute("serverError","服务器异常，请稍后再试");
                flag = false;
                return "redirect:toLogin";
            }
            JSONObject json = JSON.parseObject(jsonStr);
            int code = json.getInteger("code");
            if(code==0){//登陆成功
                HttpSession session  = request.getSession();
                session.setAttribute("account",account);
//                if(account.getSite()==null){
//                    attr.addFlashAttribute("serverError","该账号还没有在本系统注册");
//                    flag = false;
//                    return "redirect:toLogin";
//                }
                session.setAttribute("siteId",account.getSite().getId());
                flag = true;
            }else{//密码错误
                attr.addFlashAttribute("passwordError",json.getString("message"));
                flag = false;
                return "redirect:toLogin";
            }
        }
        if(flag){
            return "redirect:index";
        }else{
            return "redirect:toLogin";
        }
    }


    /**
     * 登录成功后跳转页面
     * @param modelMap
     * @return
     */
    @RequestMapping("/index")
    public String index(ModelMap modelMap){
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        User user = UserCenter.getUserByName(account.getUsername());
        account.setNickName(user.getNickName());
//        List<Site> siteList = siteService.findAll();
        List<Site> siteList = siteService.list();
        Integer siteId = (Integer) session.getAttribute("siteId");
        Site site = siteService.findOne(siteId);
        if(site==null){//如果数据库里没有该站点记录，则新建一条记录
            site = siteService.findBySiteId(siteId);
            siteService.add(site);
        }
        modelMap.put("account",account);
        modelMap.put("sites",siteList);
        modelMap.put("siteId",siteId);
        return "main/index";
    }

    /**
     * 重新向session中放入siteID  以便后面的功能使用
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/setSite",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String setSite(Integer siteId){ //id从配置系统来，如果id在本系统没有数据，那就新建一条
        Site site = siteService.findOne(siteId);
        if(site==null){
            site = siteService.findBySiteId(siteId);
            siteService.add(site);
        }
        HttpSession session = request.getSession();
        session.setAttribute("siteId",siteId);
        return ResultJson.successMeg("");
    }

}
